import type { Ast, Expression, Token } from '@/types/retrieval-sql'
import Target from './Target'

const priority = ['OR', 'AND', 'NOT']
export function joinExpression(expression: Expression, token: Token, previous: Token | undefined) {
  const operation = token.value as Expression['operation']
  // 存在优先关系
  if (previous && previous.value !== ')' && priority.includes(expression.operation) && priority.indexOf(operation) > priority.indexOf(expression.operation)) {
    // 过去未出现优先
    if (!expression.right) {
      expression.right = {
        type: 'Expression',
        operation,
        variant: 'operation',
        left: expression.left,
        start: expression.left!.start,
        end: token.end,
      }
      return expression
    }
    // 出现优先级
    expression.right = {
      type: 'Expression',
      operation: token.value as any,
      variant: 'operation',
      left: expression.right,
      start: expression.right.start,
      end: token.end,
    }
    return expression
  }

  // 无优先连接
  return <Expression>{
    type: 'Expression',
    operation: token.value as any,
    variant: 'operation',
    left: expression,
    start: expression!.start,
    end: token.end,
  }
}
export default function parser(tokens: Token[]): Ast | null {
  return new Target(tokens).walk()
}
